package com.szsky.sky.service.impl.app;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.szsky.sky.entity.app.UmcAppSn;
import com.szsky.sky.mapper.app.UmcAppSnMapper;
import com.szsky.sky.service.app.UmcAppSnService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

@Slf4j
@Service
public class UmcAppSnServiceImpl extends ServiceImpl<UmcAppSnMapper, UmcAppSn> implements UmcAppSnService {

    @Value("${spring.profiles.active}")
    private String active;

    @Resource
    private UmcAppSnMapper umcAppSnMapper;

    @Override
    public UmcAppSn getSn(String appKey) {
        Integer profilesNum = 0;
        if (StringUtils.equals(active,"prod")) {
            profilesNum = 1;
        }
        LambdaQueryWrapper<UmcAppSn> lam = new LambdaQueryWrapper<>();
        lam.eq(UmcAppSn::getAppId, appKey);
        lam.eq(UmcAppSn::getProfiles, profilesNum);
        lam.eq(UmcAppSn::getStatus, 0);
        lam.eq(UmcAppSn::getDeleteStatus, 0);
        lam.orderByAsc(UmcAppSn::getId);
        lam.last("LIMIT 1 FOR UPDATE");
        UmcAppSn umcAppSn = umcAppSnMapper.selectOne(lam);
        updateSn(umcAppSn.getSn());
        return umcAppSn;
    }

    @Override
    public Integer updateSn(String sn) {
        LambdaUpdateWrapper<UmcAppSn> lam = new LambdaUpdateWrapper<>();
        lam.set(UmcAppSn::getStatus, 1);
        lam.set(UmcAppSn::getUseTime, new Date());
        lam.eq(UmcAppSn::getSn, sn);
        Integer updateCount = umcAppSnMapper.update(lam);

        if (updateCount > 0) {
            log.info("兑换码：{}，已设置为已使用！", sn);
        } else {
            log.info("兑换码：{}，没有设置为已使用！", sn);
        }
        return updateCount;
    }
}
